package com.group4.DB;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.group4.DAO.ChannelDAO;
import com.group4.DAO.ForumDAO;

public class Channel {
	
	private int channelId;
	private int ownerId;
	private String channelName;
	
	static PreparedStatement ps = null;
	static ResultSet rs = null;
	
	
	
	public static boolean addChannel(ChannelDAO channel) {

		boolean result = false;

		if (ConnectionManager.conn == null) {
			System.out.println("Connection is null.");
			return result;
		}

		PreparedStatement ps = null;
		try {
			ps = ConnectionManager.conn
					.prepareStatement(" insert into tbl_channel (owner_id, channel_name)"
							+ " values (?, ?)");

			ps.setInt(1, channel.getOwnerId());
			ps.setString(2, channel.getChannelName());

			ps.executeUpdate();

			result = true;
		} catch (SQLException e) {
			System.out.println("SQL Error in addChannel. ");
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println("Exception in addChannel. ");
			e.printStackTrace();
		} finally {
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					System.out.println("SQL Error in addChannel. ");
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
	public static List<ChannelDAO> getChannels(int ownerId) {
		List<ChannelDAO> channelList = new ArrayList<ChannelDAO>();
		ChannelDAO channel = null;
		try {
			ps = ConnectionManager.conn.prepareStatement("select * from tbl_channel where owner_id = ?");

			ps.setInt(1, ownerId);

			rs = ps.executeQuery();

			while (rs.next()) {
				channel = new ChannelDAO();
				channel.setID(rs.getInt("channel_id"));
				channel.setOwnerId(ownerId);
				channel.setChannelName(rs.getString("channel_name"));
				channelList.add(channel);
			}
		} catch (SQLException e) {
			System.out.println("SQL Error in getting channel with ownerId");
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println("Error in getting channel with ownerId");
			e.printStackTrace();
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					System.out.println("SQL Error in getting channel with ownerId in finally");
					e.printStackTrace();
				}
			}
		}
		return channelList;
	}



}
